package com.ruihang.generalibrary.ui.util;

import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.util.ArrayMap;

import java.lang.ref.WeakReference;

/**
 * Created by rh008 on 2017/7/26.
 */

public class FragmentDialogShowHelper {

    private ArrayMap<String, WeakReference<DialogFragment>> list;

    /**
     * 是否处于onResumed状态
     */
    private boolean isResuming;

    public FragmentDialogShowHelper() {
        list = new ArrayMap<>();
    }

    public void onResume(@NonNull FragmentManager manager) {
        isResuming = true;
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                WeakReference<DialogFragment> wdf = list.valueAt(i);
                if (wdf != null && wdf.get() != null) {
//                    wdf.get().show(manager, list.keyAt(i));
                    showDialogs(manager, wdf.get(), list.keyAt(i));
                }
            }
            list.clear();
        }
    }

    public void onSaveStation() {
        isResuming = false;
    }

    public void onPause() {
        isResuming = false;
    }

    public void onDestory() {
        list.clear();
        list = null;
    }

    public void showDialog(@NonNull FragmentManager manager, @NonNull DialogFragment fragment, @NonNull String tag) {
        if (isResuming) {
//            fragment.show(manager,tag);

            showDialogs(manager, fragment, tag);
        } else {
            list.put(tag, new WeakReference<DialogFragment>(fragment));
        }
    }

    private void showDialogs(@NonNull FragmentManager manager, @NonNull DialogFragment fragment, @NonNull String tag) {
        if (fragment.isAdded()) {
            FragmentTransaction ft = manager.beginTransaction();
            if (fragment.isHidden()) {
                ft.show(fragment);
            }
            ft.commit();
        } else {
//            ft.add(fragment, tag);
            fragment.show(manager, tag);
        }
    }

    public boolean isResuming() {
        return isResuming;
    }
}
